package com.sdy.healthcode.web.controller;

import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.EncodeUtil;
import com.sdy.healthcode.biz.constants.Constants;
import com.sdy.healthcode.biz.constants.RedisConstants;
import com.sdy.healthcode.biz.model.Manager;
import com.sdy.healthcode.biz.model.Region;
import com.sdy.healthcode.biz.service.ManagerService;
import com.sdy.healthcode.biz.service.RegionService;
import com.sdy.healthcode.biz.service.UserActionService;
import com.sdy.healthcode.biz.service.UserService;
import com.sdy.healthcode.web.vo.RegionVO;
import com.sdy.healthcode.web.vo.WebUserInfoVO;
import com.sdy.mvc.controller.BaseController;
import com.sdy.redis.service.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.security.KeyPair;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zzq on 2019/1/10.
 */
@Slf4j
@RestController
@RequestMapping("/index")
@Api(tags = "基础信息接口")
public class IndexController extends BaseController {
    @Autowired
    private RedisService redisService;
    @Value("${res.app.code}")
    private String appCode;
    @Autowired
    private UserService userService;
    @Autowired
    private RegionService regionService;
    @Autowired
    private UserActionService userActionService;
    @Autowired
    private ManagerService managerService;

    @GetMapping("/publicKey")
    @ApiIgnore
    public Response publicKey(HttpServletRequest request) throws Exception {
        KeyPair keyPair = EncodeUtil.rsaGenKeyPair();
        String publicKeyStr = new String(Base64.getEncoder().encode(keyPair.getPublic().getEncoded()));
        redisService.set(RedisConstants.REDIS_PREFIX + "privateKey_" + getUserId(request), Base64.getEncoder().encode(keyPair.getPrivate().getEncoded()));
        return Response.success(publicKeyStr);
    }

    @GetMapping("/webUserInfo")
    @ApiOperation(value = "获取当前用户基本信息")
    public Response<WebUserInfoVO> webUserInfo(HttpServletRequest request) {
        Integer userId = getUserId(request, Constants.SESSION_WEB_USER_ID);
        Manager manager = managerService.getById(userId);

        if (manager == null) {
            return Response.error();
        }
        WebUserInfoVO userInfoVO = new WebUserInfoVO();
        userInfoVO.setName(manager.getName());
        return Response.success(userInfoVO);
    }
    
    @GetMapping("/region")
    @ApiOperation(value = "本地市街道信息")
    public Response region() {
        Map<String, RegionVO> m = new HashMap<>();
        List<Region> regionList = regionService.listRegionByProvinceAndCity(Constants.REGION_PROVINCE_NAME, Constants.REGION_CITY_NAME);
        regionList.forEach(region -> {
            m.put(region.getCityCode(), new RegionVO().setParent(null).setName(region.getCityName()).setValue(region.getCityCode()));
            m.put(region.getAreaCode(), new RegionVO().setParent(region.getCityCode()).setName(region.getAreaName()).setValue(region.getAreaCode()));
            m.put(region.getStreetCode(), new RegionVO().setParent(region.getAreaCode()).setName(region.getStreetName()).setValue(region.getStreetCode()));
        });
        return Response.success(m.values());
    }

    @GetMapping("/area")
    @ApiOperation(value = "本地市区县信息")
    public Response area() {
        Map<String, RegionVO> m = new HashMap<>();
        List<Region> regionList = regionService.listAreaByProvinceAndCity(Constants.REGION_PROVINCE_NAME, Constants.REGION_CITY_NAME);
        regionList.forEach(region -> {
            m.put(region.getProvinceCode(), new RegionVO().setParent(null).setName(region.getProvinceName()).setValue(region.getProvinceCode()));
            m.put(region.getCityCode(), new RegionVO().setParent(region.getProvinceCode()).setName(region.getCityName()).setValue(region.getCityCode()));
            m.put(region.getAreaCode(), new RegionVO().setParent(region.getCityCode()).setName(region.getAreaName()).setValue(region.getAreaCode()));
        });
        return Response.success(m.values());
    }

    @PostMapping("/modifyPassword")
    @ApiOperation(value = "修改密码")
    public Response modifyPassword(HttpServletRequest request, @RequestBody Map<String, String> params) throws Exception {
        String passwordOld = params.get("passwordOld");
        String passwordNew = params.get("password");
        Integer userId = getUserId(request, Constants.SESSION_WEB_USER_ID);
        Assert.isNull(userId, "用户id不能为空");
        Assert.isBlank(passwordNew, "新密码不能为空");
        Manager user = managerService.getById(userId);
        Assert.isTrue(!user.getPassword().equals(passwordOld), "密码错误");
        managerService.lambdaUpdate().eq(Manager::getId, userId).set(Manager::getPassword, passwordNew).update();
        return Response.success();
    }
}
